package com.tyqx.hashchainbiz.controller.user.auth;

import com.tyqx.hashchainbean.module.SystemConfig;
import com.tyqx.hashchainbean.module.TrackUser;
import com.tyqx.hashchainbean.vo.TrackUserVO;
import com.tyqx.hashchainbiz.controller.config.JwtTokenUtil;
import com.tyqx.hashchainbiz.service.HashChainPasswordService;
import com.tyqx.hashchainbiz.service.SystemConfigService;
import com.tyqx.hashchainbiz.service.TrackUserRegisterService;
import com.tyqx.hashchainbiz.service.TrackUserService;
import com.tyqx.hashchainbiz.service.impl.JwtUserDetailsService;
import com.tyqx.hashchainutil.common.*;
import hashchainutil.common.Dto;
import hashchainutil.common.DtoUtil;
import hashchainutil.common.EmptyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: dcep-spring
 * @description:
 * @author: Mr.Li
 * @create: 2020-04-19 00:16
 **/
@Api(description = "用户注册")
@RestController
@CrossOrigin
public class TrackUserRegisterController {


    @Resource
    private TrackUserRegisterService trackUserRegisterService;

    @Resource
    private TrackUserService trackUserService;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private HashChainPasswordService hashChainPasswordService;

    @Resource
    private SystemConfigService systemConfigService;


    Logger logger = LoggerFactory.getLogger(this.getClass());


    @ApiOperation(value = "用户注册", httpMethod = "POST",
            produces = "application/json",
            response = Dto.class,
            notes = "用户注册信息  成功返回结果 DcepUserVO \n" +
                    "{\n" +
                    "\n  \"success\": \"true\",\n" +
                    "\n  \"errorCode\": \"0\",\n" +
                    "\n  \"msg\": \"\",\n" +
                    "\n  \"data\": {\n" +
                    "\n  }\n" +
                    "\n}\n"+
                    "\n用户注册错误码: \n"+
                    "\n100001:新增注册信息失败\n"+
                    "\n100012:未知错误\n")
    @RequestMapping(value = "registerTrackUser", method = RequestMethod.POST,
            produces = "application/json")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Dto registerTrackUser(@RequestBody TrackUser trackUser) throws Exception {

        CreateWallet createWallet = new CreateWallet();
        SystemConfig systemConfig=systemConfigService.selectSystemConfigByKey("isRegisterEnabled");
        if(EmptyUtils.isEmpty(systemConfig)){
            return DtoUtil.returnFail("用户注册未开放","100001");
        }else if(!"true".equals(systemConfig.getConfigValue())){
            return DtoUtil.returnFail("用户注册未开放","100001");
        }
        Long caIndex = 1L;
        String orgType = "peer";
        String tlsCaType = "tls";
        String mspCaType = "msp";
        Long orgIndex = 0L;
        String COMPOSE_PROJECT_NAME="hashchain";
        String interCAUserName="admin";
        String interCAName="INTER_CA_"+caIndex;
        String channelName="hashchainchannel";
        String chaincodeName="hashchainmanage";
        //String interCAPassword="pw_547979523200181472916229201187521344832173328519751062613389251752311018325";
        String interCAPassword=hashChainPasswordService.getHashChainPasswordByName(interCAName,COMPOSE_PROJECT_NAME,interCAUserName).getNodePassword();

        String rootCAUserName="admin";
        String rootCAName="ROOT_CA";
        //String rootCAPassword="pw_24486625430075265982825523258209602390110776175952378525373138006015143411492";
        String rootCAPassword=hashChainPasswordService.getHashChainPasswordByName(rootCAName,COMPOSE_PROJECT_NAME,rootCAUserName).getNodePassword();


        TrackUser trackUser1=new TrackUser();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);

        trackUser1.setCreateTime(sdf.parse(time));
        trackUser1.setUserName(trackUser.getUserName());
        trackUser1.setPassword(trackUser.getPassword());
        trackUser1.setPhone(trackUser.getPhone());
        trackUser1.setZipCode(trackUser.getZipCode());
        trackUser1.setAccount(trackUser.getAccount());
        trackUser1.setAddress(trackUser.getAddress());
        trackUser1.setCompanyName(trackUser.getCompanyName());
        trackUser1.setContact(trackUser.getContact());
        trackUser1.setRepresent(trackUser.getRepresent());
        try {
            if(trackUserService.getUserByCode(trackUser1.getUserName())!=null){
                return DtoUtil.returnFail("用户名已存在", "100013");
            }else{
                //新增User
                if (trackUserRegisterService.saveNewUser(trackUser1)) {
                    logger.info("新增用户信息成功");
                    //createWallet.addPeerOrgUser(COMPOSE_PROJECT_NAME,caIndex,trackUser.getPassword(),orgIndex,trackUser.getUserName());
                    //ChainCode chainCode=new ChainCode();
                    //chainCode.setBalance(COMPOSE_PROJECT_NAME,trackUser.getUserName(),1000,channelName,chaincodeName,"setBalance");
                    //将密码暂时设为原密码 用于免登录
                    TrackUserVO trackUserVO = trackUserService.login(trackUser.getUserName(), trackUser.getPassword());
                    logger.debug("自注册用户免登录");
                    logger.info("登录成功");
                    final UserDetails userDetails = userDetailsService
                            .loadUserByUsername(trackUser.getUserName());

                    final String token = jwtTokenUtil.generateToken(userDetails);
                    trackUserVO.setToken(token);

                    return DtoUtil.returnDataSuccess(trackUserVO,"注册成功");
                }
            }
        } catch (Exception e) {
            throw new Exception();
        }
        logger.error("运行出错");
        return DtoUtil.returnFail("未知错误", "100012");
    }
}
